package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.UserException;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public User loadUserByUsername(String username) {
        //根据用户名查询用户信息（id，密码）
        User user = userMapper.findByUserName(username);
        if (null != user) {
            //根据id查询用户的权限集合
            //1、根据用户id查询用户所有的角色
            Set<Role> roles = roleMapper.findByUserId(user.getId());
            if (CollectionUtil.isNotEmpty(roles)) {
                //2、循环角色集合查询角色对应的权限集合
                for (Role role : roles) {
                    Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public List<Menu> findAllMenu() {
        //先查一级所有的菜单
        List<Menu> oneMenu = userMapper.findOneMenu();
        //再查二级所有的菜单
        for (Menu menu : oneMenu) {
            List<Menu> twoMenu = userMapper.findMenuByParentMenuId(menu.getId());
            for (Menu childMenu : twoMenu) {
                List<Menu> childs = userMapper.findMenuByParentMenuId(childMenu.getId());
                childMenu.setChildren(childs);
            }
            menu.setChildren(twoMenu);
        }
        return oneMenu;

    }

    @Override
    public void doAdd(Menu menu) {
        //先判断菜单名是否存在相同的
        Integer count = userMapper.selectCountByName(menu);
        //菜单名相同，报错，不添加
        if (count != null && count > 0) {
            throw new UserException("菜单名已存在，无法添加");
        } else {
            //判断当前菜单是否为一级菜单
            if (menu.getParentMenuId() == null) {
                //说明是一级菜单
                List<Menu> oneMenu = userMapper.findOneMenu();
                menu.setPath(String.valueOf(oneMenu.size() + 1));
                menu.setPriority(1);
                menu.setLevel(1);
                userMapper.insertMenu(menu);
            } else {
                //不是一级菜单
                //查询父级菜单
                Menu parentMenu = userMapper.findParentMenuById(menu.getParentMenuId());
                //根据父级id查询当前已存在的子菜单个数
                Integer childs = userMapper.findByParentMenuId(menu.getParentMenuId());
                menu.setLevel(parentMenu.getLevel() + 1);
                if (menu.getLevel() == 2) {
                    menu.setPath("/" + parentMenu.getPath() + "-" + (childs + 1));
                } else {
                    menu.setPath(parentMenu.getPath() + "-" + (childs + 1));
                }
                menu.setPriority(childs + 1);
                userMapper.insertMenu(menu);
            }
        }


    }

    @Override
    public void remove(Integer id) {
        //先查看当前菜单是否被引用
        Integer count = userMapper.findCountByMenuId(id);
        if (count != null && count > 0) {
            throw new UserException("当前菜单被引用，无法删除");
        } else {
            //查看当前菜单下是否有子菜单，如果有子菜单，先删除子菜单
            List<Integer> ids = userMapper.findChildMenuByParentMenuId(id);
            if (ids != null) {
                for (Integer childId : ids) {
                    List<Integer> childIds = userMapper.findChildMenuByParentMenuId(childId);
                    if (childIds != null) {
                        for (Integer cid : childIds) {
                            userMapper.removeMenuById(cid);
                        }
                    }
                    userMapper.removeMenuById(childId);
                }
            }
            userMapper.removeMenuById(id);
        }


    }

    @Override
    public Menu findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public void edit(Menu menu) {
        //先查询是否有名字冲突的
        Integer count = userMapper.findCountByMenu(menu);
        if (count != null && count > 0) {
            throw new UserException("该菜单名名字已存在");
        } else {
            userMapper.edit(menu);
        }

    }

    @Override
    public PageResult findRightPage(QueryPageBean queryPageBean) {
        //使用分页插件(告诉mybatis 我要分页)
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //写一个普普通通的查询sql
        List<Menu> menus = userMapper.findRightPage();

//        Page<CheckItem> page = checkItemMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),menus);
    }
}
